using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using PersonalBudgeting;
using PersonalBudgeting.Models;
using Serilog;
using System;
using System.IO;

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .Enrich.FromLogContext()
            .CreateLogger();

        // ��������� ������������ �� appsettings.json
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .Build();

        // �������� ������ �����������
        string connectionString = configuration.GetConnectionString("DefaultConnection");

        // ������� DbContext
        var optionsBuilder = new DbContextOptionsBuilder<PersonalBudgetingContext>();
        optionsBuilder.UseNpgsql(connectionString); // ���������, ��� � ��� ���������� ����� Npgsql.EntityFrameworkCore.PostgreSQL

        using (var context = new PersonalBudgetingContext(optionsBuilder.Options))
        {
            Console.WriteLine("����������� � ���� ������ �����������!");
            context.Database.Migrate();
            Console.WriteLine("�������� ���������.");
        }

        try
        {
            Log.Information("Starting web host");            
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog() // ���������� Serilog
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
